﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ElectronStoreDAL;
using BackEnd.Technical;
using System.Data.Entity;

namespace BackEnd
{
	public partial class Product : Technical.UserAutentification
	{
		private ElectronStoreSource dataSource;
		private ElectronStoreDAL.Product product;
		private int idCategory;
		private int idProduct;
		private string pathImage = string.Empty;


		public List<ElectronStoreDAL.Category> ListCategory
		{
			get
			{
				if (dataSource != null)
					return dataSource.GetCategories();
				else
					return null;
			}
		}


		protected void Page_Load(object sender, EventArgs e)
		{
			dataSource = new ElectronStoreSource();

			int.TryParse(Request.Params["catId"], out idCategory);
			if (int.TryParse(Request.Params["prodId"], out idProduct))
			{
				if (idProduct > 0)
					product = dataSource.GetProductById(idProduct);
			}
		}


		protected void Page_PreRender(object sender, EventArgs e)
		{
			if (!IsPostBack)
			{
				if (product != null)
				{
					tbxName.Text = product.Name;
					tbxPrice.Text = product.CurrentPrice.ToString();
					if (!string.IsNullOrEmpty(product.Info))
						tbxInfo.Text = product.Info;
					string path = PathManager.UrlSmallImage(product.ProductID);
					if (System.IO.File.Exists(Server.MapPath(path)))
						imgProduct.ImageUrl = path;
				}

				if (ListCategory != null)
				{
					ddlCategory.DataSource = ListCategory;
				}

				Page.DataBind();

				if (ddlCategory.Items != null)
				{
					ListItem item = ddlCategory.Items.FindByValue(idCategory.ToString());
					if (item != null)
						item.Selected = true;
				}
			}
		}


		protected void btnLoad_Click(object sender, EventArgs e)
		{
			if (fuploadImg.HasFile)
			{
				ElectronStoreSource.Buffer = new byte[fuploadImg.PostedFile.ContentLength];
				fuploadImg.PostedFile.InputStream.Read(ElectronStoreSource.Buffer, 0, ElectronStoreSource.Buffer.Length);
				imgProduct.ImageUrl = GeneralResource.urlImageHandler;
			}
		}


		protected void btnSave_Click(object sender, EventArgs e)
		{
			if (fuploadImg.HasFile)
				fuploadImg.SaveAs(Server.MapPath(string.Format(GeneralResource.urlSmallImages, fuploadImg.FileName)));

		}


		protected void btnCancel_Click(object sender, EventArgs e)
		{
			Response.Redirect(string.Format(GeneralResource.urlCatalog, idCategory));
		}

	}	//public partial class Product

}	//namespace BackEnd